package com.bailiban.controller;

import com.bailiban.PasswordEncoder;
import com.bailiban.entity.Role;
import com.bailiban.entity.Users;
import com.bailiban.service.RoleService;
import com.bailiban.service.UsersService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author zhulang
 * @Classname UserController
 * @Description UserController
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private RoleService roleService;

    @GetMapping("findAll")
    @PreAuthorize("hasAnyRole('ROLE_USER','ROLE_ADMIN')")
    public ModelAndView findAll(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "3") Integer size) {
        PageInfo<Users> pageInfo = usersService.findAll(page, size);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user-page-list");
        modelAndView.addObject("userP", pageInfo);
        return modelAndView;
    }

    @GetMapping("findById")
    public ModelAndView findById(Integer id) {
        Users users = usersService.queryById(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user-show");
        modelAndView.addObject("users", users);
        return modelAndView;
    }

    @PostMapping("save")
    @PreAuthorize("authentication.principal.username=='zl' or hasRole('ROLE_BOSS')")
    public String save(Users users) {
        //将用户的密码加密
        String password = PasswordEncoder.passwordEncoder(users.getPassword());
        users.setPassword(password);
        Users insert = usersService.insert(users);
        return "redirect:/user/findAll.do";
    }

    @GetMapping("findUserByIdAndAllRole")
    public ModelAndView findUserByIdAndAllRole(Integer id) {
        List<Role> roleList = roleService.findOtherRoleByUserId(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user-role-add");
        modelAndView.addObject("roleList", roleList);
        modelAndView.addObject("userId", id);
        return modelAndView;
    }

    @PostMapping("addRoleToUser")
    public String addRoleToUser(Integer userId, Integer[] ids) {
        usersService.save(userId, ids);
        return "redirect:/user/findAll.do";
    }
}
